package pen_exam.meituan_2023_10_14;


import com.sun.xml.internal.fastinfoset.tools.TransformInputOutput;

import java.util.PriorityQueue;
import java.util.Scanner;

//糖果店 n种糖果无限供应，所有糖果2元一个
//购买ai个糖果 就可享受1元购买第i种糖果，小红购买第i种糖果bi个，最少需要多少钱？
//第一行n 糖果种类
//第二行ai 购买ai个糖果就可享受1元购买第i种糖果
//第三行bi 需要i种bi个
public class Class01_Candy {

    public static class Node {
        public int free;
        public int buy;
    }


    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        sc.nextLine();
        String[] str1 = sc.nextLine().split(" ");
        String[] str2 = sc.nextLine().split(" ");
        Node[] candy = new Node[n];
        int[] a = new int[n];
        int[] b = new int[n];
        PriorityQueue<Node> MinFreeQueue = new PriorityQueue<>((x, y) -> {
            return x.free - y.free;
        });
        PriorityQueue<Node> MoreBuyQueue = new PriorityQueue<>((x, y) -> {
            return y.buy - x.buy;
        });
        for (int i = 0; i < n; i++) {
            candy[i] = new Node();
            candy[i].free = Integer.parseInt(str1[i]);
            candy[i].buy = Integer.parseInt(str2[i]);
            MinFreeQueue.add(candy[i]);
            MoreBuyQueue.add(candy[i]);
        }
        int ans = 0;
        int cost = 0;
        while (!MinFreeQueue.isEmpty() && !MoreBuyQueue.isEmpty()) {
            Node curMinFree = MinFreeQueue.peek();
            int minFree = curMinFree.free;
            Node cur = MoreBuyQueue.peek();
            if (ans + cur.buy >= minFree) {
                //买到打折
                MinFreeQueue.remove(curMinFree);
                cur.buy -=  minFree - ans;
                ans +=  minFree - ans;
                cost += 2 * (minFree - ans);
            }else{
                //不够到下次
                cost += 2 * cur.buy;
                cur.buy = 0;
                ans += cur.buy;
            }
            if(curMinFree.buy == 0){
                MoreBuyQueue.remove(curMinFree);
            }
//            if (ans == minFree) {
//                curMinFree.buy--;
//                ans++;
//                cost += 1;
//            }
//            if (curMinFree.buy == 0) {
//                MoreBuyQueue.remove(curMinFree);
//            }
//            if (cur.buy == 0) {
//                MoreBuyQueue.remove(cur);
//            }
//            if(ans < minFree && curMinFree.buy > 0){
//                MinFreeQueue.add(curMinFree);
//            }
        }
        while (!MoreBuyQueue.isEmpty()) {
            Node cur = MoreBuyQueue.poll();
            cost += 2 * cur.buy;
        }
        System.out.println(cost);
    }
}
